package cn.wzb.hrm.service.impl;

import cn.wzb.hrm.domain.Employee;
import cn.wzb.hrm.domain.Meal;
import cn.wzb.hrm.domain.Tenant;
import cn.wzb.hrm.dto.TenantDto;
import cn.wzb.hrm.mapper.EmployeeMapper;
import cn.wzb.hrm.mapper.TenantMapper;
import cn.wzb.hrm.service.ITenantService;
import cn.wzb.hrm.util.encrypt.MD5;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author whale.chen
 * @since 2020-04-19
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void entering(TenantDto tenantDto) {

        Tenant tenant = tenantDto.getTenant();
        Employee employee = tenantDto.getEmployee();
        Long mealId = tenantDto.getMealId();

        //判断基本参数
        if(!StringUtils.hasLength(tenant.getCompanyName())){
            throw new RuntimeException("公司名字不能为空");
        }
        if(!StringUtils.hasLength(tenant.getCompanyNum())){
            throw new RuntimeException("公司执照不能为空");
        }
        if(!StringUtils.hasLength(tenant.getAddress())){
            throw new RuntimeException("公司地址不能为空");
        }

        //先保存机构tenant,员工需要根据机构的id保存
        Tenant tenant1 = new Tenant();

        tenant1.setAddress(tenant.getAddress());
        tenant1.setCompanyName(tenant.getCompanyName());
        tenant1.setCompanyNum(tenant.getCompanyNum());
        tenant1.setLogo(tenant.getLogo());
        tenant1.setTenantType(tenant.getTenantType());

        //前台没传的字段,自己设置
        Date date = new Date();
        tenant1.setRegisterTime(date);
        tenant1.setState(Tenant.STATE_NORMAL);

        baseMapper.insert(tenant1);//不要把前台页面传过来的数据直接保存

        //保存员工-->不要直接insert
        Employee employee1 = new Employee();

        employee1.setEmail(employee.getEmail());

        //密码要不要加密
        String enPass = MD5.getMD5(employee.getPassword() + "itsource");

        employee1.setPassword(enPass);
        employee1.setTel(employee.getTel());
        employee1.setUsername(employee.getUsername());
        employee1.setState(Employee.STATE_NORMAL);
        employee1.setInputTime(date);
        employee1.setTenantId(tenant1.getId());
        employee1.setType(Employee.TYPE_ADMIN);

        employeeMapper.insert(employee1);

        //保存租户和套餐关系 ： t_tenant_meal
        baseMapper.insertRelationWithMeal(mealId ,tenant1.getId() , Meal.STATE_UN_PAY );
    }
}
